package com.oocl.scan.service;

import com.alibaba.fastjson.JSONObject;
import com.oocl.scan.utils.JsonUtil;
import com.oocl.scan.utils.PropertiesUtil;
import com.oocl.scan.utils.StringUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedQueue;

public class SaveService<T> {

  private static final String DK_SERVER_PATH_NAME = "dk_server_path";
  private static final String MAX_SEND_RECORD = "max_send_records";

  private static final String DK_SERVER_PATH;
  private static final String MAX_RECORD_COUNT;

  static {
    DK_SERVER_PATH = PropertiesUtil.getPropertyByName(DK_SERVER_PATH_NAME);
    MAX_RECORD_COUNT = PropertiesUtil.getPropertyByName(MAX_SEND_RECORD);
  }

  public String sendPost(String params) {
    OutputStreamWriter out = null;
    BufferedReader reader = null;
    String response = "";

    try {
      HttpURLConnection conn = getConnection();
      out = new OutputStreamWriter(conn.getOutputStream());
      out.write(params);
      out.flush();
      reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String lines;
      while ((lines = reader.readLine()) != null) {
        lines = new String(lines.getBytes(), "utf-8");
        response += lines;
      }
      reader.close();
      conn.disconnect();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (reader != null) {
          reader.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return response;
  }

  private HttpURLConnection getConnection() throws Exception {
    URL httpUrl = new URL(DK_SERVER_PATH);
    HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("accept", "application/json");
    conn.setUseCaches(false);//设置不要缓存
    conn.setInstanceFollowRedirects(true);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.connect();
    return conn;
  }

  private void printResult(String response) {
    if (StringUtil.isNotEmpty(response) && (Boolean) JSONObject.parseObject(response).get("data") && JSONObject.parseObject(response).get("error") == null) {
      System.out.println("save successful");
    } else {
      System.out.println("save failed");
    }
  }

  public void saveToDISystem(String type, LinkedList<T> list) {
    int recordCount = Integer.parseInt(MAX_RECORD_COUNT);
    int times = list.size() / recordCount;
    int preCount = 0;
    int sufCount = 0;
    for (int i = 0; i < times; i++) {
      sufCount = preCount + recordCount - 1;
      sendSubRecord(preCount, sufCount, type, list);
      preCount = sufCount + 1;
    }
    sufCount = list.size() - 1;
    sendSubRecord(preCount, sufCount, type, list);
  }

  public void saveToDISystem(String type, ConcurrentLinkedQueue<T> list) {
    String params = "{\"" + type + "\":" + JsonUtil.convertObject(list) + "}";
    printResult(sendPost(params));
  }

  private void sendSubRecord(int preCount, int sufCount, String type, LinkedList<T> list) {
    String params = "{\"" + type + "\":" + JsonUtil.convertObject(list.subList(preCount, sufCount)) + "}";
    printResult(sendPost(params));
  }
}
